<template>
    <el-card shadow="never" class="border-0">
        <!-- 搜索 -->
        <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
            <el-row :gutter="20">
                <el-col :span="5" :offset="0">
                    <el-form-item label="用户名">
                        <el-input v-model="searchForm.username" placeholder="用户名" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="手机号">
                        <el-input v-model="searchForm.phone" placeholder="手机号" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="14">
                    <div class="flex items-center justify-end">
                        <el-button type="primary" @click="getData(1)">搜索</el-button>
                        <el-button @click="resetSearchForm">重置</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form>


        <!-- 新增|刷新 -->
        <div class="flex items-center justify-between mb-4">
            <el-tooltip effect="dark" content="刷新数据" placement="top">
                <el-button text @click="getData">
                    <el-icon :size="20">
                        <Refresh />
                    </el-icon>
                </el-button>
            </el-tooltip>
        </div>

        <!-- 表格数据 -->
        <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
            <el-table-column label="用户名" align="center">
                <template #default="{ row }">
                    {{ row.username }}
                </template>
            </el-table-column>

            <el-table-column label="真实姓名" align="center">
                <template #default="{ row }">
                    {{ row.realName }}
                </template>
            </el-table-column>

            <el-table-column label="手机号" align="center">
                <template #default="{ row }">
                    {{ row.phone }}
                </template>
            </el-table-column>

            <el-table-column label="邮箱" align="center">
                <template #default="{ row }">
                    {{ row.email }}
                </template>
            </el-table-column>

            <el-table-column label="性别" align="center">
                <template #default="{ row }">
                    {{ transferSex(row.sex) }}
                </template>
            </el-table-column>

            <el-table-column label="状态" align="center">
                <template #default="{ row }">
                    {{ transferPcState(row.status) }}
                </template>
            </el-table-column>

            <el-table-column label="创建时间" align="center">
                <template #default="{ row }">
                    {{ dateFormatter(row.createTime) }}
                </template>
            </el-table-column>


            <el-table-column label="操作" width="300" align="center">
                <template #default="scope">
                    <small v-if="scope.row.super == 1" class="text-sm text-gray-500">暂无操作</small>
                    <div v-else>

                        <el-popconfirm title="是否要恢复该用户？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="chageUserStatus(scope.row.id, 1)">
                            <template #reference>
                                <el-button v-if="scope.row.status == 2" type="primary" size="small" text>恢复</el-button>
                            </template>
                        </el-popconfirm>

                        <el-popconfirm title="是否要挂起该用户？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="chageUserStatus(scope.row.id, 2)">
                            <template #reference>
                                <el-button v-if="scope.row.status == 1" type="primary" size="small" text>挂起</el-button>
                            </template>
                        </el-popconfirm>

                        <el-button type="primary" size="small" text @click="handleEdit(scope.row)">修改</el-button>

                        <el-popconfirm title="是否要初始化密码？" confirmButtonText="确认" cancelButtonText="取消"
                            @confirm="initPwd(scope.row.id)">
                            <template #reference>
                                <el-button text type="primary" size="small">重置密码</el-button>
                            </template>
                        </el-popconfirm>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
                :page-size="limit" @current-change="getData" />
        </div>

        <!-- 新增|修改弹窗 -->
        <FormDrawer ref="formDrawerRef" :title="drawerTitle" @submit="handleSubmit">

            <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">

                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" placeholder="用户名"></el-input>
                </el-form-item>

                <el-form-item label="真实姓名" prop="realName">
                    <el-input v-model="form.realName" placeholder="真实姓名"></el-input>
                </el-form-item>

                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="form.phone" placeholder="手机号"></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="邮箱"></el-input>
                </el-form-item>

                <el-form-item label="性别" prop="sex">
                    <el-select v-model="form.sex" placeholder="性别">
                        <el-option key="1" label="男" value="1"></el-option>
                        <el-option key="2" label="女" value="2"></el-option>
                    </el-select>
                </el-form-item>

            </el-form>
        </FormDrawer>

    </el-card>

    <el-dialog v-model="resetpasswordDialogVisible" title="重置密码结果" width="500" align-center>
        <text>{{ resetpasswordDialogResult }}</text>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="resetpasswordDialogVisible = false">
                    关闭
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, reactive, computed, onMounted } from "vue"
import FormDrawer from "~/components/FormDrawer.vue";
import {
    getBoatsmanList,
    updateManagerStatus,
    createManager,
    updateManager,
    deleteManager,
    resetpassword
} from "~/api/manager"
import { getRoleList } from "~/api/role";
import {
    toast
} from "~/composables/util"
import { useStore } from 'vuex'
import { transferSex, transferPcState, dateFormatter } from '~/utils/common.js'
import { checkPhone, checkEmail } from '~/utils/validate.js'
import { isDeveloper } from '~/utils/userInfo.js'

// 分页
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)
const resetpasswordDialogVisible = ref(false)
const resetpasswordDialogResult = ref('')
const store = useStore()
//是否是开发者账号
const developer = ref(false)
// 查询条件
const searchForm = reactive({
    username: "",
    phone: "",
    page: currentPage.value,
    size: limit.value,
})
// 重置搜索框
const resetSearchForm = () => {
    searchForm.username = ""
    searchForm.phone = ""
    getData(1)
}

const roles = ref([])
const tableData = ref([])
const loading = ref(false)


// 生命周期函数
onMounted(() => {
    //判断是否是开发者账号登录
    if (isDeveloper()) {
        developer.value = true
    }

    //初始化角色字典数据
    getRoleList().then(res => {
        if (res) {
            if (developer.value) {
                roles.value = res.records.filter(function (item) {
                    return item.name != "engineer" && item.name != "companyManager";
                });
            } else {
                roles.value = res.records.filter(function (item) {
                    return item.name != "engineer" && item.name != "companyManager" && item.name != "developer";
                });
            }
        }
    })

    //初始化列表数据
    getData()
})

//角色字典数据，数据转换方法
const formatRoleName = (roleId) => {
    //console.log(roles)
    return roles.value.find(x => x.id == roleId)?.description || roleId
}

// 获取数据
function getData(p = null) {
    if (typeof p == "number") {
        currentPage.value = p
    }

    loading.value = true
    searchForm.page = currentPage.value
    getBoatsmanList(currentPage.value, searchForm)
        .then(res => {
            //console.log(res.records)
            if (res) {
                tableData.value = res.records
                total.value = res.total
            } else {
                tableData.value = []
                total.value = 0
            }
        })
        .finally(() => {
            loading.value = false
        })
}

// 删除
const handleDelete = (id) => {
    loading.value = true
    deleteManager(id).then(res => {
        toast("删除成功")
        getData()
    })
        .finally(() => {
            loading.value = false
        })
}

// 表单部分
const formDrawerRef = ref(null)
const formRef = ref(null)
const form = reactive({
    username: "",
    realName: "",
    phone: "",
    roleId: null,
    email: "",
    sex: "1"
})
//执行表单校验
const rules = {
    username: [
        { required: true, message: '请填写用户名', trigger: 'change' }
    ],
    realName: [
        { required: true, message: '请填写用户真实名', trigger: 'change' }
    ],
    phone: [
        { validator: checkPhone, required: true, trigger: 'change' }
    ],
    roleId: [
        { required: true, message: '请选择用户角色', trigger: 'change' }
    ],
    email: [
        { validator: checkEmail, required: true, trigger: 'change' }
    ]
}

//是否是编辑弹窗
const editId = ref(0)
const drawerTitle = computed(() => editId.value ? "修改" : "新增")

//提交表单
const handleSubmit = () => {
    //表单校验
    formRef.value.validate((valid) => {
        if (!valid) return

        //loading
        formDrawerRef.value.showLoading()

        //根据是否是修改标记，判断执行新增接口还是修改接口
        const fun = editId.value ? updateManager(editId.value, form) : createManager(form)

        fun.then(res => {
            toast(drawerTitle.value + "成功")
            // 修改刷新当前页，新增刷新第一页
            getData(editId.value ? false : 1)
            formDrawerRef.value.close()
        })
            .finally(() => {
                //close loading
                formDrawerRef.value.hideLoading()
            })
    })
}

// 重置表单
function resetForm(row = false) {
    if (formRef.value) formRef.value.resetFields()
    if (row) {
        for (const key in form) {
            form[key] = row[key]
        }
    }
}

// 新增按钮点击事件
const handleCreate = () => {
    //修改标记置为0
    editId.value = 0
    resetForm({
        username: "",
        realName: "",
        phone: "",
        roleId: null,
        email: "",
        sex: "1",
    })
    //打开弹窗
    formDrawerRef.value.open()
}

// 编辑
const handleEdit = (row) => {
    editId.value = row.id
    resetForm(row)
    formDrawerRef.value.open()
}

// 获取|挂起用户
const chageUserStatus = (id, status) => {
    loading.value = true
    updateManagerStatus(id, status).then(res => {
        if (status == "1") {
            toast("恢复成功")
        } else {
            toast("挂起成功")
        }
        getData()
    })
        .finally(() => {
            loading.value = false
        })
}

// 修改状态
const initPwd = (userId) => {
    resetpassword(userId).then((res) => {
        resetpasswordDialogVisible.value = true
        resetpasswordDialogResult.value = res
    })
}

</script>